package com.manager.devicemanager.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manager.devicemanager.annotation.OperateLog;
import com.manager.devicemanager.common.OperationTypeEnum;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.entity.DeviceInfo;
import com.manager.devicemanager.entity.UserInfo;
import com.manager.devicemanager.service.IComponentStatusService;
import com.manager.devicemanager.service.IDeviceInfoService;
import com.manager.devicemanager.service.IDeviceUserService;
import com.manager.devicemanager.service.IUserInfoService;
import com.manager.devicemanager.vo.DeviceInfoVO;
import com.manager.devicemanager.vo.PageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备表 前端控制器
 * </p>
 *
 * @author wpf
 * @since 2025-05-27
 */
@Tag(name = "DeviceInfoController", description = "设备表 相关接口")
@RestController
@RequestMapping("/deviceInfo")
public class DeviceInfoController {

    @Autowired
    private IDeviceInfoService iDeviceInfoService;
    @Autowired
    private IDeviceUserService identityUserService;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private IComponentStatusService iComponentStatusService;

    @Operation(summary = "新增")
    @OperateLog(operationType = OperationTypeEnum.ADD, operationDesc = "新增设备")
    @PostMapping("/save")
    public Result<DeviceInfo> save(@Parameter(description = "DeviceInfo 对象") @RequestBody DeviceInfo deviceInfo){
       iDeviceInfoService.save(deviceInfo);
        return Result.success(deviceInfo);
    }

    @Operation(summary = "按id删除")
    @OperateLog(operationType = OperationTypeEnum.DELETE, operationDesc = "删除设备")
    @PostMapping("/delete/{id}")
    public Result<String> delete(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id){
       iDeviceInfoService.removeById(id);
        return Result.success(id);
    }

    @Operation(summary = "按id修改")
    @OperateLog(operationType = OperationTypeEnum.UPDATE, operationDesc = "修改设备信息")
    @PostMapping("/update/{id}")
    public Result<DeviceInfo> update(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id, @Parameter(description = "DeviceInfo 对象") @RequestBody DeviceInfo deviceInfo){
        deviceInfo.setId(id);
       iDeviceInfoService.updateById(deviceInfo);
        return Result.success(deviceInfo);
    }

    @Operation(summary = "按id查询")
    @GetMapping("/get/{id}")
    public Result<DeviceInfo> get(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id){
        DeviceInfo deviceInfo =iDeviceInfoService.getById(id);
        return Result.success(deviceInfo);
    }

    @Operation(summary = "条件查询带分页")
    @PostMapping("/page")
    public Result<IPage<DeviceInfoVO>> page(@Parameter(description = "查询条件对象") @RequestBody  PageVO<DeviceInfo> deviceInfoQuery){
        int pageNum = deviceInfoQuery.getPageNum();
        int pageSize = deviceInfoQuery.getPageSize();
        DeviceInfo deviceInfo = deviceInfoQuery.getCondition();
         QueryWrapper<DeviceInfo> wrapper =new QueryWrapper<>(deviceInfo);
        //if (StringUtils.hasText(deviceInfo.getName())) {
          //  wrapper.like("name", deviceInfo.getName());
        //}
        IPage<DeviceInfo> deviceInfoList =iDeviceInfoService.page(new Page<>(pageNum, pageSize),wrapper);
        List<DeviceInfoVO> collect = deviceInfoList.getRecords().stream().map(deviceInfo1 -> {
            DeviceInfoVO deviceInfoVO = new DeviceInfoVO();
            BeanUtils.copyProperties(deviceInfo1, deviceInfoVO);
            // 获取设备配置的用户信息
            List<UserInfo> userInfoList = iDeviceInfoService.getDeviceUserList(deviceInfo1.getId());
            deviceInfoVO.setUsers(userInfoList);
            return deviceInfoVO;
        }).collect(Collectors.toList());

        // 创建一个新的 IPage<DeviceInfoVO> 对象，并设置分页信息和转换后的记录
        IPage<DeviceInfoVO> deviceInfoVOList = new Page<>(
                deviceInfoList.getCurrent(),
                deviceInfoList.getSize(),
                deviceInfoList.getTotal()
        );
        deviceInfoVOList.setRecords(collect);

        return Result.success(deviceInfoVOList);
    }

    @Operation(summary = "条件查询")
    @PostMapping("/list")
    public Result<List<DeviceInfoVO>> list(@Parameter(description = "DeviceInfo 查询条件对象") @RequestBody DeviceInfo deviceInfo){
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>(deviceInfo);
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        List<DeviceInfoVO> deviceInfoVOStream = deviceInfoList.stream().map(deviceInfo1 -> {
            DeviceInfoVO deviceInfoVO = new DeviceInfoVO();
            BeanUtils.copyProperties(deviceInfo1, deviceInfoVO);
            // 获取设备配置的用户信息
            List<UserInfo> userInfoList = iDeviceInfoService.getDeviceUserList(deviceInfo1.getId());
            deviceInfoVO.setUsers(userInfoList);
            return deviceInfoVO;
        }).collect(Collectors.toList());
        return Result.success(deviceInfoVOStream);
    }

    @Operation(summary = "地图")
    @PostMapping("/maplist")
    public Result<List<JSONObject>> maplist(@Parameter(description = "DeviceInfo 查询条件对象") @RequestBody DeviceInfo deviceInfo){
        // 创建查询条件包装器，并按 deviceindex 升序排序
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>(deviceInfo);
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        List<JSONObject> deviceInfoVOStream = deviceInfoList.stream().map(deviceInfo1 -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", deviceInfo1.getName());
            jsonObject.put("value", Arrays.asList(deviceInfo1.getLng(),deviceInfo1.getLat()));
            return jsonObject;
        }).collect(Collectors.toList());
        return Result.success(deviceInfoVOStream);
    }


    @Operation(summary = "设备用户列表")
    @PostMapping("/deviceuserlist/{id}")
    public Result<List<UserInfo>> getDeviceUserList(@PathVariable(name ="设备id")  String id){
        List<UserInfo> userInfoList =iDeviceInfoService.getDeviceUserList(id);
        return Result.success(userInfoList);
    }
    @PostMapping("deviceruninfo")
    public Result<List<JSONObject>> getDeviceRunInfo(){
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DeviceInfo::getDeviceindex);
        List<DeviceInfo> deviceInfoList = iDeviceInfoService.list(queryWrapper);
        List<JSONObject> deviceRunInfoStream = deviceInfoList.stream().map(deviceInfo1 -> {
            String type = deviceInfo1.getType();
            String datasourceindex = deviceInfo1.getDatasourceindex();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("devicename", deviceInfo1.getName());
            jsonObject.put("type", type);
            jsonObject.put("datasourceindex", datasourceindex);
            jsonObject.put("value", Arrays.asList(deviceInfo1.getLng(),deviceInfo1.getLat()));
            return jsonObject;
        }).collect(Collectors.toList());
        return Result.success(deviceRunInfoStream);
    }

}
